import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, filedialog
import datetime
import os
import sys
import json
from pathlib import Path
from typing import List, Dict, Any, Tuple, Optional, Set

current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.append(project_root)

from System.UserSystem import UserSystem
from System.CourseSystem import CourseSystem
from System.AssignmentSystem import AssignmentSystem
from User.Student import Student
from Course.Course import Course
from Assignment.Assignment import Assignment, AssignmentSubmission

# ------------------------------
# 1. Global style configuration (adjusted based on user feedback)
# ------------------------------
def SetupStyle():
    style = ttk.Style()
    
    # Set global font
    default_font = ("Microsoft YaHei", 10)
    style.configure(".", font=default_font)
    
    # Frame styles
    style.configure("Main.TFrame", background="#f8f9fa")
    style.configure("Card.TFrame", background="#ffffff", borderwidth=1, relief="solid", bordercolor="#E5E7EB")
    
    # Button styles - Primary button (optimized visual effect)
    style.configure("Primary.TButton", background="#1E40AF", foreground="#1E40AF", 
                   font=("Microsoft YaHei", 10, "bold"), padding=8, borderwidth=0, relief="flat")
    style.map("Primary.TButton", background=[("active", "#3B82F6"), ("disabled", "#94A3B8")],
             foreground=[("disabled", "#E2E8F0")])
    
    # Button styles - Secondary button (optimized visual effect)
    style.configure("Secondary.TButton", background="#E0F2FE", foreground="#1E40AF",
                   font=("Microsoft YaHei", 10), padding=8, borderwidth=0, relief="flat")
    style.map("Secondary.TButton", background=[("active", "#BAE6FD"), ("disabled", "#F1F5F9")])
    
    # Title styles (optimized font size)
    style.configure("Title.TLabel", font=("Microsoft YaHei", 12, "bold"), background="#f8f9fa", foreground="#1F2937")
    style.configure("SubTitle.TLabel", font=("Microsoft YaHei", 12, "bold"), background="#ffffff", foreground="#1F2937")
    
    # Text styles
    style.configure("Normal.TLabel", font=("Microsoft YaHei", 10), background="#ffffff", foreground="#1F2937")
    style.configure("Small.TLabel", font=("Microsoft YaHei", 9), background="#ffffff", foreground="#6B7280")
    
    # Status label styles
    style.configure("Success.TLabel", font=("Microsoft YaHei", 10, "bold"), background="#ffffff", foreground="#10B981")
    style.configure("Warning.TLabel", font=("Microsoft YaHei", 10, "bold"), background="#ffffff", foreground="#F59E0B")
    style.configure("Error.TLabel", font=("Microsoft YaHei", 10, "bold"), background="#ffffff", foreground="#EF4444")
    
    # Entry style
    style.configure("TEntry", font=("Microsoft YaHei", 10), padding=8, borderwidth=1, relief="solid", 
                   fieldbackground="white", bordercolor="#D1D5DB")
    style.map("TEntry", bordercolor=[("focus", "#1E40AF")], relief=[("focus", "solid")])
    
    # Treeview style
    style.configure("Treeview.Heading", font=("Microsoft YaHei", 10, "bold"), background="#1E40AF", 
                   foreground="white", padding=8)
    style.configure("Treeview", font=("Microsoft YaHei", 9), rowheight=28, background="white", fieldbackground="white")
    style.map("Treeview", background=[("selected", "#DBEAFE"), ("alternate", "#F9FAFB")],
             foreground=[("selected", "#1E40AF")])
    
    # Scrollbar style
    style.configure("Vertical.TScrollbar", background="#E5E7EB", troughcolor="#f8f9fa", arrowcolor="#6B7280")
    style.map("Vertical.TScrollbar", background=[("active", "#CBD5E1")])

# ------------------------------
# 2. Student Information Window
# ------------------------------
class StudentInfoWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, student: Student):
        super().__init__(parent)
        self.title(f"Personal Information - {student.ChineseName}")
        self.geometry("450x350")
        self.resizable(False, False)
        self.configure(bg="#f8f9fa")
        
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        title_label = ttk.Label(main_frame, text="Basic Personal Information", style="SubTitle.TLabel")
        title_label.pack(anchor=tk.W, pady=(0, 15))
        
        info_frame = ttk.Frame(main_frame, style="Card.TFrame")
        info_frame.pack(fill=tk.BOTH, expand=True)
        
        info_rows = [
            ("Name:", student.ChineseName),
            ("Student ID:", student.ID),
            ("Username:", student.ID),
            ("Class:", student.Group if student.Group else "Not Assigned"),
            ("Enrolled Courses:", f"{len(student.Courses)} courses")
        ]
        
        for i, (label_text, value_text) in enumerate(info_rows):
            ttk.Label(info_frame, text=label_text, font=("Microsoft YaHei", 10, "bold")).grid(
                row=i, column=0, padx=20, pady=10, sticky=tk.W)
            ttk.Label(info_frame, text=value_text, style="Normal.TLabel").grid(
                row=i, column=1, padx=20, pady=10, sticky=tk.W)
        
        info_frame.grid_columnconfigure(1, weight=1)
        
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(side=tk.RIGHT, padx=10, pady=15)
        
        close_btn = ttk.Button(btn_frame, text="Close", style="Primary.TButton", command=self.destroy)
        close_btn.pack(side=tk.RIGHT)

# ------------------------------
# 3. Course Detail Window (Fixed layout conflict error)
# ------------------------------
class CourseDetailWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, course: Course, student: Student, enroll_callback: callable, drop_callback: callable):
        super().__init__(parent)
        self.parent = parent
        self.course = course
        self.student = student
        self.enroll_callback = enroll_callback
        self.drop_callback = drop_callback
        
        self.title(f"{course.CourseName} - Course Details")
        self.geometry("650x550")
        self.resizable(False, False)
        self.configure(bg="#f8f9fa")
        
        self._create_widgets()
    
    def _create_widgets(self):
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # Course basic information card - Fixed layout conflict: unified use of grid layout
        info_frame = ttk.Frame(main_frame, style="Card.TFrame")
        info_frame.pack(fill=tk.X, pady=(0, 15))
        
        # Header - Using grid instead of pack
        header_frame = ttk.Frame(info_frame)
        header_frame.grid(row=0, column=0, columnspan=2, sticky=tk.EW, pady=(10, 15))
        ttk.Label(header_frame, text="Basic Course Information", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        # Configure column weights for better layout
        info_frame.grid_columnconfigure(1, weight=1)
        
        info_rows = [
            ("Course ID:", self.course.ID),
            ("Course Name:", self.course.CourseName),
            ("Teacher:", self.course.Teacher.ChineseName),
            ("Course Time:", self.course.CourseTime),
            ("Classroom:", self.course.Classroom)
        ]
        
        for i, (label_text, value_text) in enumerate(info_rows):
            ttk.Label(info_frame, text=label_text, font=("Microsoft YaHei", 10, "bold")).grid(
                row=i+1, column=0, padx=15, pady=8, sticky=tk.W)
            ttk.Label(info_frame, text=value_text).grid(
                row=i+1, column=1, padx=15, pady=8, sticky=tk.W)
        
        # Course introduction card
        intro_frame = ttk.Frame(main_frame, style="Card.TFrame")
        intro_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 15))
        
        ttk.Label(intro_frame, text="Course Introduction", style="SubTitle.TLabel").pack(
            anchor=tk.W, padx=15, pady=12)
        
        intro_text = scrolledtext.ScrolledText(intro_frame, font=("Microsoft YaHei", 10), wrap=tk.WORD)
        intro_content = getattr(self.course, "introduction", "No course introduction available")
        intro_text.insert(tk.END, intro_content)
        intro_text.config(state=tk.DISABLED, bg="#F8FAFC", relief="flat")
        intro_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0, 15))
        
        # Button area
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, anchor='e')
        
        close_btn = ttk.Button(btn_frame, text="Close", command=self.destroy, style="Secondary.TButton")
        close_btn.pack(side=tk.RIGHT, padx=5)

# ------------------------------
# 4. Course Module Interface (Fixed event binding)
# ------------------------------
class CourseModuleFrame(ttk.Frame):
    def __init__(self, parent: tk.Tk, app: "LMSApp", student: Student, user_system: UserSystem, course_system: CourseSystem):
        super().__init__(parent, style="Main.TFrame")
        self.app = app
        self.student = student
        self.user_system = user_system
        self.course_system = course_system
        self.parent = parent
        
        # Navigation bar
        nav_frame = ttk.Frame(self, style="Main.TFrame")
        nav_frame.pack(fill=tk.X, padx=20, pady=10)
        
        back_btn = ttk.Button(nav_frame, text="← Return to Main Interface", style="Secondary.TButton", command=self.back_to_main)
        back_btn.pack(anchor=tk.W)
        
        # Title area
        title_frame = ttk.Frame(self, style="Main.TFrame")
        title_frame.pack(fill=tk.X, padx=20, pady=(5, 15))
        
        ttk.Label(title_frame, text="My Courses", style="Title.TLabel").pack(anchor=tk.W)
        
        # Filter frame
        filter_frame = ttk.Frame(self, style="Main.TFrame")
        filter_frame.pack(fill=tk.X, padx=20, pady=(0, 10))
        
        ttk.Label(filter_frame, text="Course Filter:", font=("Microsoft YaHei", 10)).pack(side=tk.LEFT, padx=(0, 10))
        
        self.filter_var = tk.StringVar(value="all")
        filter_options = [
            ("All Courses", "all"),
            ("Enrolled Courses", "enrolled"),
            ("Available Courses", "available")
        ]
        
        radio_frame = ttk.Frame(filter_frame)
        radio_frame.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        for text, value in filter_options:
            ttk.Radiobutton(radio_frame, text=text, variable=self.filter_var, value=value, 
                           command=self.refresh_courses, style="TRadiobutton").pack(side=tk.LEFT, padx=10)
        
        # Add top action buttons
        action_frame = ttk.Frame(self, style="Main.TFrame")
        action_frame.pack(fill=tk.X, padx=20, pady=(0, 12))
        
        self.detail_btn = ttk.Button(
            action_frame, text="View Course Details", command=self.show_course_detail, 
            state=tk.DISABLED, style="Secondary.TButton"
        )
        self.detail_btn.pack(side=tk.LEFT, padx=5)
        
        self.action_btn = ttk.Button(
            action_frame, text="Enroll/Drop Course", command=self.perform_course_action, 
            state=tk.DISABLED, style="Primary.TButton"
        )
        self.action_btn.pack(side=tk.LEFT, padx=5)
        
        # Course table area
        self.course_frame = ttk.Frame(self, style="Card.TFrame")
        self.course_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=0)
        
        # Create responsive Treeview
        self.course_tree = ttk.Treeview(
            self.course_frame, 
            columns=("courseId", "courseName", "teacher", "courseTime", "classroom", "status"),
            show="headings"
        )
        
        # Set column headings and responsive widths
        columns = [
            ("courseId", "Course ID", 0.1),
            ("courseName", "Course Name", 0.22),
            ("teacher", "Teacher", 0.15),
            ("courseTime", "Course Time", 0.18),
            ("classroom", "Classroom", 0.15),
            ("status", "Status", 0.2)
        ]
        
        for col, heading, width_ratio in columns:
            self.course_tree.heading(col, text=heading)
            self.course_tree.column(col, width=int(width_ratio * 100), stretch=True)
        
        self.refresh_courses()
        
        # Fixed Treeview event binding - use correct event identifier
        self.course_tree.bind("<<TreeviewSelect>>", self.on_course_select)
        
        # Scrollbar
        course_scroll = ttk.Scrollbar(
            self.course_frame, orient=tk.VERTICAL, command=self.course_tree.yview
        )
        self.course_tree.configure(yscrollcommand=course_scroll.set)
        
        # Use grid layout for responsiveness
        self.course_tree.grid(row=0, column=0, sticky=tk.NSEW)
        course_scroll.grid(row=0, column=1, sticky=tk.NS)
        
        # Set weights for responsive expansion
        self.course_frame.grid_rowconfigure(0, weight=1)
        self.course_frame.grid_columnconfigure(0, weight=1)
    
    def on_course_select(self, event):
        """Handle course selection event - optimized status update logic"""
        selected_items = self.course_tree.selection()
        if len(selected_items) > 0:
            # Get selected item data
            item_id = selected_items[0]
            values = self.course_tree.item(item_id, "values")
            status = values[5]
            
            # Update button states and text
            self.detail_btn.config(state=tk.NORMAL)
            self.action_btn.config(state=tk.NORMAL)
            self.action_btn.config(text="Drop Course" if status == "Enrolled" else "Enroll Course")
        else:
            self.detail_btn.config(state=tk.DISABLED)
            self.action_btn.config(state=tk.DISABLED)
    
    def show_course_detail(self):
        """View selected course details"""
        selected_items = self.course_tree.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select a course first")
            return
            
        item_id = selected_items[0]
        course_id = self.course_tree.item(item_id, "values")[0]
        course = self.course_system.get_course_by_id(course_id)
        
        if course:
            # Check if enrolled
            is_enrolled = course_id in self.student.Courses
            
            # Create course detail window
            CourseDetailWindow(
                self, course, self.student, 
                enroll_callback=lambda: self.enroll_course(course_id),
                drop_callback=lambda: self.drop_course(course_id)
            )
        else:
            messagebox.showerror("Error", f"Course with ID {course_id} not found")
    
    def perform_course_action(self):
        """Perform enroll/drop course action - enhanced error handling"""
        selected_items = self.course_tree.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select a course first")
            return
            
        item_id = selected_items[0]
        values = self.course_tree.item(item_id, "values")
        course_id = values[0]
        course_name = values[1]
        status = values[5]
        
        if status == "Enrolled":
            # Drop course
            if messagebox.askyesno("Confirm Drop", f"Are you sure you want to drop course《{course_name}》?"):
                self.drop_course(course_id)
        else:
            # Enroll course
            if messagebox.askyesno("Confirm Enroll", f"Are you sure you want to enroll in course《{course_name}》?"):
                self.enroll_course(course_id)
    
    def enroll_course(self, course_id):
        """Enroll in a course"""
        try:
            success, msg = self.course_system.AddStudentToCourse(course_id, self.student.ID)
            if success:
                messagebox.showinfo("Enrollment Successful", msg)
                if course_id not in self.student.Courses:
                    self.student.Courses.append(course_id)
                self.refresh_courses()
            else:
                messagebox.showerror("Enrollment Failed", msg)
        except Exception as e:
            messagebox.showerror("Error", f"Error during enrollment: {str(e)}")
    
    def drop_course(self, course_id):
        """Drop a course"""
        try:
            success, msg = self.course_system.RemoveStudentFromCourse(course_id, self.student.ID)
            if success:
                messagebox.showinfo("Drop Successful", msg)
                if course_id in self.student.Courses:
                    self.student.Courses.remove(course_id)
                self.refresh_courses()
            else:
                messagebox.showerror("Drop Failed", msg)
        except Exception as e:
            messagebox.showerror("Error", f"Error during course drop: {str(e)}")
    
    def refresh_courses(self):
        """Refresh course list"""
        # Clear existing data
        for item in self.course_tree.get_children():
            self.course_tree.delete(item)
            
        # Get course data
        all_courses = self.course_system.get_all_courses()
        self.course_data = []
        
        for course in all_courses:
            is_enrolled = course.ID in self.student.Courses
            
            # Set different color tags based on status
            if is_enrolled:
                status = "Enrolled"
                tag = "enrolled"
            else:
                status = "Available"
                tag = "available"
                
            self.course_data.append({
                "courseId": course.ID,
                "courseName": course.CourseName,
                "teacher": course.Teacher.EnglishName,
                "courseTime": course.CourseTime,
                "classroom": course.Classroom,
                "status": status,
                "enrolled": is_enrolled,
                "original_course": course,
                "tag": tag
            })
        
        # Filter courses
        filter_type = self.filter_var.get()
        filtered_courses = []
        
        for course in self.course_data:
            if filter_type == "all":
                filtered_courses.append(course)
            elif filter_type == "enrolled" and course["enrolled"]:
                filtered_courses.append(course)
            elif filter_type == "available" and not course["enrolled"]:
                filtered_courses.append(course)
        
        # Add to table
        for course in filtered_courses:
            self.course_tree.insert("", tk.END, values=(
                course["courseId"],
                course["courseName"],
                course["teacher"],
                course["courseTime"],
                course["classroom"],
                course["status"]
            ), tags=(course["tag"],))
        
        # Reset button states
        self.detail_btn.config(state=tk.DISABLED)
        self.action_btn.config(state=tk.DISABLED)
    
    def back_to_main(self):
        self.app.ShowStudentMainFrame()

# ------------------------------
# 4. Assignment Submission Window
# ------------------------------
class HomeworkSubmitWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, homework: Assignment, submit_callback: callable):
        super().__init__(parent)
        self.parent = parent
        self.homework = homework
        self.submit_callback = submit_callback
        self.selected_file_path = ""
        self.is_expired = self._check_expired()
        
        self.title(f"Submit Assignment - {homework.Title}")
        self.geometry("700x600")
        self.resizable(True, True)
        self.minsize(600, 500)
        self.configure(bg="#f8f9fa")
        
        # Use grid layout for responsiveness
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        
        try:
            self._create_widgets()
        except Exception as e:
            messagebox.showerror("Initialization Error", f"Failed to create submission window: {str(e)}")
            self.destroy()
    
    def _check_expired(self) -> bool:
        try:
            return datetime.datetime.now() > self.homework.Deadline
        except Exception as e:
            messagebox.showerror("Date Error", f"Failed to parse deadline: {str(e)}")
            return True
    
    def _create_widgets(self):
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.grid(row=0, column=0, sticky=tk.NSEW, padx=20, pady=20)
        
        # Configure main frame for responsiveness
        main_frame.grid_rowconfigure(2, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)
        
        # Assignment basic information card
        info_frame = ttk.Frame(main_frame, style="Card.TFrame")
        info_frame.grid(row=0, column=0, sticky=tk.EW, pady=(0, 15))
        
        # Header area - using grid layout
        header_frame = ttk.Frame(info_frame)
        header_frame.grid(row=0, column=0, columnspan=2, sticky=tk.EW, pady=(10, 15))
        ttk.Label(header_frame, text="Basic Assignment Information", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        info_rows = [
            ("Assignment ID:", self.homework.ID),
            ("Course Name:", self.homework.Course.CourseName),
            ("Assignment Title:", self.homework.Title),
            ("Deadline:", self.homework.Deadline.strftime("%Y-%m-%d %H:%M")),
        ]
        
        for i, (label_text, value_text) in enumerate(info_rows):
            ttk.Label(info_frame, text=label_text, font=("Microsoft YaHei", 10, "bold")).grid(
                row=i+1, column=0, padx=15, pady=8, sticky=tk.W)
            ttk.Label(info_frame, text=value_text).grid(
                row=i+1, column=1, padx=15, pady=8, sticky=tk.W)
        
        # Expiration warning - using grid layout
        if self.is_expired:
            expired_frame = ttk.Frame(info_frame)
            expired_frame.grid(row=5, column=0, columnspan=2, padx=15, pady=8, sticky=tk.W)
            ttk.Label(expired_frame, text="⚠️ ", font=("Microsoft YaHei", 10)).pack(side=tk.LEFT)
            ttk.Label(expired_frame, text="Assignment has expired, cannot submit", style="Warning.TLabel").pack(side=tk.LEFT)
        
        # File upload area card
        file_frame = ttk.Frame(main_frame, style="Card.TFrame")
        file_frame.grid(row=1, column=0, sticky=tk.EW, pady=(0, 15))
        
        # File upload area title
        file_header = ttk.Frame(file_frame)
        file_header.pack(fill=tk.X, pady=(10, 15))
        ttk.Label(file_header, text="File Upload", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        # Responsive file selection area
        file_path_frame = ttk.Frame(file_frame)
        file_path_frame.pack(fill=tk.X, padx=15, pady=(0, 15))
        
        self.file_path_entry = ttk.Entry(file_path_frame, state="readonly", font=("Microsoft YaHei", 10))
        self.file_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=(0, 10))
        
        select_file_btn = ttk.Button(
            file_path_frame, text="Select File", command=self.select_file, 
            state="disabled" if self.is_expired else "normal", style="Secondary.TButton"
        )
        select_file_btn.pack(side=tk.RIGHT)
        
        # Assignment description card
        note_frame = ttk.Frame(main_frame, style="Card.TFrame")
        note_frame.grid(row=2, column=0, sticky=tk.NSEW, pady=(0, 15))
        
        # Assignment description title
        note_header = ttk.Frame(note_frame)
        note_header.pack(fill=tk.X, pady=(10, 15))
        ttk.Label(note_header, text="Assignment Notes (Optional)", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        self.note_text = scrolledtext.ScrolledText(
            note_frame, font=("Microsoft YaHei", 10), wrap=tk.WORD, 
            state="disabled" if self.is_expired else "normal", bg="#F8FAFC"
        )
        self.note_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0, 15))
        
        # Button area
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=3, column=0, sticky=tk.E, pady=10)
        
        cancel_btn = ttk.Button(btn_frame, text="Cancel", command=self.destroy, style="Secondary.TButton")
        cancel_btn.pack(side=tk.RIGHT, padx=5)
        
        self.submit_btn = ttk.Button(
            btn_frame, text="Confirm Submission", command=self.confirm_submit, 
            state="disabled" if self.is_expired else "normal", style="Primary.TButton"
        )
        self.submit_btn.pack(side=tk.RIGHT)
    
    def select_file(self):
        file_types = [
            ("Document Files", "*.pdf;*.doc;*.docx"),
            ("Image Files", "*.jpg;*.png"),
            ("Code Files", "*.py;*.java;*.cpp"),
            ("All Files", "*.*")
        ]
        
        file_path = filedialog.askopenfilename(title="Select Assignment File", filetypes=file_types)
        if file_path:
            self.selected_file_path = file_path
            display_path = file_path if len(file_path) <= 50 else f"{file_path[:30]}...{file_path[-15:]}"
            
            self.file_path_entry.config(state=tk.NORMAL)
            self.file_path_entry.delete(0, tk.END)
            self.file_path_entry.insert(0, display_path)
            self.file_path_entry.config(state=tk.READABLE)
    
    def confirm_submit(self):
        if self.is_expired:
            messagebox.showerror("Submission Failed", "Assignment has expired, cannot submit!")
            return
            
        if not self.selected_file_path:
            messagebox.showerror("Submission Error", "Please select a file to upload first!")
            return
            
        try:
            with open(self.selected_file_path, 'rb') as f:
                file_content = f.read()
                
            note_content = self.note_text.get("1.0", tk.END).strip()
            
            if self.submit_callback:
                success, msg = self.submit_callback(
                    assignment_id=self.homework.ID,
                    student_id=self.parent.student.ID,
                    content=f"File content: {os.path.basename(self.selected_file_path)}\nAssignment notes: {note_content}"
                )
                
                if success:
                    messagebox.showinfo(
                        "Submission Successful", 
                        f"Assignment submitted successfully!\nSubmission time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\nFile: {os.path.basename(self.selected_file_path)}"
                    )
                    self.destroy()
                else:
                    messagebox.showerror("Submission Failed", msg)
        except Exception as e:
            messagebox.showerror("Submission Failed", f"Error during submission: {str(e)}")

# ------------------------------
# 5. Assignment Detail Window (Added teacher grade display)
# ------------------------------
class HomeworkDetailWindow(tk.Toplevel):
    def __init__(self, parent: tk.Tk, homework: Assignment, submit_callback: callable):
        super().__init__(parent)
        self.parent = parent
        self.homework = homework
        self.submit_callback = submit_callback
        
        self.title(f"{homework.Title} - Assignment Details")
        self.geometry("700x600")
        self.resizable(True, True)
        self.minsize(650, 550)
        self.configure(bg="#f8f9fa")
        
        # Use grid layout for responsiveness
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        
        self._create_widgets()
    
    def _create_widgets(self):
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.grid(row=0, column=0, sticky=tk.NSEW, padx=20, pady=20)
        
        # Configure main frame for responsiveness
        main_frame.grid_rowconfigure(2, weight=1)
        main_frame.grid_columnconfigure(0, weight=1)
        
        # Assignment basic information card - unified use of grid layout
        info_frame = ttk.Frame(main_frame, style="Card.TFrame")
        info_frame.grid(row=0, column=0, sticky=tk.EW, pady=(0, 15))
        
        # Header area - using grid layout
        header_frame = ttk.Frame(info_frame)
        header_frame.grid(row=0, column=0, columnspan=2, sticky=tk.EW, pady=(10, 15))
        ttk.Label(header_frame, text="Basic Assignment Information", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        # Check if submitted
        student = self.parent.student
        is_submitted = self.homework.is_submitted_by(student)
        
        # Get grade information
        grade = None
        if is_submitted:
            # Find current student's submission record
            for submission in self.homework.Submissions:
                if submission.student.ID == student.ID:
                    grade = submission.grade
                    break
        
        # Calculate status
        now = datetime.datetime.now()
        if is_submitted:
            status = "Submitted"
            status_style = "Success.TLabel"
        elif now > self.homework.Deadline:
            status = "Expired"
            status_style = "Warning.TLabel"
        else:
            status = "Not Submitted"
            status_style = "Normal.TLabel"
        
        # Basic information rows
        info_rows = [
            ("Assignment ID:", self.homework.ID),
            ("Course Name:", self.homework.Course.CourseName),
            ("Assignment Title:", self.homework.Title),
            ("Deadline:", self.homework.Deadline.strftime("%Y-%m-%d %H:%M")),
            ("Current Status:", status)
        ]
        
        # Add grade information row if available
        if grade is not None:
            info_rows.append(("Teacher's Grade:", f"{grade} points"))
        
        # Unified use of grid layout
        for i, (label_text, value_text) in enumerate(info_rows):
            ttk.Label(info_frame, text=label_text, font=("Microsoft YaHei", 10, "bold")).grid(
                row=i+1, column=0, padx=15, pady=8, sticky=tk.W)
            
            # Use special style for grade information
            if label_text == "Teacher's Grade:":
                ttk.Label(info_frame, text=value_text, style="Success.TLabel").grid(
                    row=i+1, column=1, padx=15, pady=8, sticky=tk.W)
            elif label_text == "Current Status:":
                ttk.Label(info_frame, text=value_text, style=status_style).grid(
                    row=i+1, column=1, padx=15, pady=8, sticky=tk.W)
            else:
                ttk.Label(info_frame, text=value_text).grid(
                    row=i+1, column=1, padx=15, pady=8, sticky=tk.W)
        
        # Submission information (if submitted)
        if is_submitted:
            submit_info_frame = ttk.Frame(info_frame)
            submit_info_frame.grid(row=len(info_rows)+1, column=0, columnspan=2, padx=15, pady=12, sticky=tk.W)
            ttk.Label(submit_info_frame, text="Submission Information", style="SubTitle.TLabel").pack(anchor=tk.W)
            
            details_frame = ttk.Frame(submit_info_frame)
            details_frame.pack(fill=tk.X, pady=5)
        
        # Assignment requirements card
        req_frame = ttk.Frame(main_frame, style="Card.TFrame")
        req_frame.grid(row=1, column=0, sticky=tk.NSEW, pady=(0, 15))
        
        # Title area
        req_header = ttk.Frame(req_frame)
        req_header.pack(fill=tk.X, pady=(10, 15))
        ttk.Label(req_header, text="Assignment Requirements", style="SubTitle.TLabel").pack(anchor=tk.W, padx=15)
        
        req_text = scrolledtext.ScrolledText(req_frame, font=("Microsoft YaHei", 10), wrap=tk.WORD)
        req_text.insert(tk.END, self.homework.Description)
        req_text.config(state=tk.DISABLED, bg="#F8FAFC", relief="flat")
        req_text.pack(fill=tk.BOTH, expand=True, padx=15, pady=(0, 15))
        
        # Button area
        btn_frame = ttk.Frame(main_frame)
        btn_frame.grid(row=2, column=0, sticky=tk.E, pady=10)
        
        close_btn = ttk.Button(btn_frame, text="Close", command=self.destroy, style="Secondary.TButton")
        close_btn.pack(side=tk.RIGHT, padx=5)
        
        # Submit/resubmit button
        if status != "Expired":
            submit_btn_text = "Submitted" if is_submitted else "Submit Assignment"
            submit_btn = ttk.Button(
                btn_frame, text=submit_btn_text, command=self.open_submit_window, style="Primary.TButton"
            )
            submit_btn.pack(side=tk.RIGHT, padx=5)
    
    def open_submit_window(self):
        try:
            HomeworkSubmitWindow(
                parent=self.parent, homework=self.homework, submit_callback=self.submit_assignment
            )
        except Exception as e:
            messagebox.showerror("Error", f"Failed to open submission window: {str(e)}")

# ------------------------------
# 6. Assignment Module Interface (Removed quick submit function)
# ------------------------------
class HomeworkModuleFrame(ttk.Frame):
    def __init__(self, parent: tk.Tk, app: "LMSApp", student: Student, user_system: UserSystem, 
                 course_system: CourseSystem, assignment_system: AssignmentSystem):
        super().__init__(parent, style="Main.TFrame")
        self.app = app
        self.student = student
        self.user_system = user_system
        self.course_system = course_system
        self.assignment_system = assignment_system
        self.parent = parent
        
        # Navigation bar
        nav_frame = ttk.Frame(self, style="Main.TFrame")
        nav_frame.pack(fill=tk.X, padx=20, pady=10)
        
        back_btn = ttk.Button(nav_frame, text="← Return to Main Interface", style="Secondary.TButton", command=self.back_to_main)
        back_btn.pack(anchor=tk.W)
        
        # Title area
        title_frame = ttk.Frame(self, style="Main.TFrame")
        title_frame.pack(fill=tk.X, padx=20, pady=(5, 15))
        
        ttk.Label(title_frame, text="My Assignments", style="Title.TLabel").pack(anchor=tk.W)
        
        # Top action button area - Removed quick submit button
        action_frame = ttk.Frame(self, style="Main.TFrame")
        action_frame.pack(fill=tk.X, padx=20, pady=(0, 12))
        
        self.detail_btn = ttk.Button(
            action_frame, text="View Assignment Details", command=self.show_homework_detail, 
            state=tk.DISABLED, style="Secondary.TButton"
        )
        self.detail_btn.pack(side=tk.LEFT, padx=5)
        
        self.submit_btn = ttk.Button(
            action_frame, text="Submit Assignment", command=self.direct_submit_homework, 
            state=tk.DISABLED, style="Primary.TButton"
        )
        self.submit_btn.pack(side=tk.LEFT, padx=5)
        
        # Assignment table area
        self.homework_frame = ttk.Frame(self, style="Card.TFrame")
        self.homework_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=0)
        
        # Create responsive Treeview
        self.homework_tree = ttk.Treeview(
            self.homework_frame, 
            columns=("homeworkId", "courseName", "title", "deadline", "status", "days_left"),
            show="headings"
        )
        
        # Set column headings and responsive widths
        columns = [
            ("homeworkId", "Assignment ID", 0.1),
            ("courseName", "Course Name", 0.2),
            ("title", "Assignment Title", 0.22),
            ("deadline", "Deadline", 0.18),
            ("status", "Status", 0.15),
            ("days_left", "Days Left", 0.15)
        ]
        
        for col, heading, width_ratio in columns:
            self.homework_tree.heading(col, text=heading)
            self.homework_tree.column(col, width=int(width_ratio * 100), stretch=True)
        
        # Fixed Treeview event binding
        self.homework_tree.bind("<<TreeviewSelect>>", self.on_homework_select)
        
        # Load assignment data
        self.load_homework_data()
        
        # Scrollbar
        homework_scroll = ttk.Scrollbar(
            self.homework_frame, orient=tk.VERTICAL, command=self.homework_tree.yview
        )
        self.homework_tree.configure(yscrollcommand=homework_scroll.set)
        
        # Use grid layout for responsiveness
        self.homework_tree.grid(row=0, column=0, sticky=tk.NSEW)
        homework_scroll.grid(row=0, column=1, sticky=tk.NS)
        
        # Set weights for responsive expansion
        self.homework_frame.grid_rowconfigure(0, weight=1)
        self.homework_frame.grid_columnconfigure(0, weight=1)
    
    def on_homework_select(self, event):
        """Handle assignment selection event"""
        selected_items = self.homework_tree.selection()
        if len(selected_items) > 0:
            # Get selected item data
            item_id = selected_items[0]
            values = self.homework_tree.item(item_id, "values")
            status = values[4]
            
            # Update button states
            self.detail_btn.config(state=tk.NORMAL)
            
            # Enable/disable submit button based on status
            if "Expired" in status:
                self.submit_btn.config(state=tk.DISABLED)
                self.submit_btn.config(text="Expired")
            elif "Not Submitted" == status:
                self.submit_btn.config(state=tk.NORMAL)
                self.submit_btn.config(text="Submit")
            else:
                self.submit_btn.config(state=tk.DISABLED)
                self.submit_btn.config(text="Submited")
        else:
            self.detail_btn.config(state=tk.DISABLED)
            self.submit_btn.config(state=tk.DISABLED)
    
    def show_homework_detail(self):
        """View selected assignment details"""
        selected_items = self.homework_tree.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select an assignment first")
            return
            
        item_id = selected_items[0]
        homework_id = self.homework_tree.item(item_id, "values")[0]
        
        # Find corresponding assignment object
        homework = None
        for hw_data in self.homework_data:
            if hw_data["homeworkId"] == homework_id:
                homework = hw_data["homework"]
                break
                
        if homework:
            HomeworkDetailWindow(self, homework, self.submit_assignment)
        else:
            messagebox.showerror("Error", f"Assignment with ID {homework_id} not found")
    
    def direct_submit_homework(self):
        """Submit selected assignment"""
        selected_items = self.homework_tree.selection()
        if not selected_items:
            messagebox.showwarning("提示", "Please select an assignment first")
            return
            
        item_id = selected_items[0]
        values = self.homework_tree.item(item_id, "values")
        homework_id = values[0]
        status = values[4]
        
        if "Expired" in status:
            messagebox.showinfo("提示", "This assignment has expired and cannot be submitted")
            return
            
        # Find corresponding assignment object
        homework = None
        for hw_data in self.homework_data:
            if hw_data["homeworkId"] == homework_id:
                homework = hw_data["homework"]
                break
                
        if homework:
            HomeworkSubmitWindow(
                parent=self, homework=homework, submit_callback=self.submit_assignment
            )
        else:
            messagebox.showerror("Error", f"Assignment with ID {homework_id} not found")
    
    def load_homework_data(self):
        """Load actual assignment data from assignment system"""
        # Clear existing data
        for item in self.homework_tree.get_children():
            self.homework_tree.delete(item)
            
        # Get data from assignment system
        self.homework_data = []
        now = datetime.datetime.now()
        
        # Get all assignments for student's enrolled courses
        for course_id in self.student.Courses:
            course_assignments = self.assignment_system.get_assignments_by_course(course_id)
            for assignment in course_assignments:
                # Calculate days left
                time_diff = assignment.Deadline - now
                days_left = time_diff.days
                
                # Calculate status and tag
                if assignment.is_submitted_by(self.student):
                    status = "Submitted"
                    tag = "submitted"
                elif now > assignment.Deadline:
                    status = "Expired"
                    tag = "expired"
                else:
                    status = "Not Submitted"
                    tag = "pending"
                
                # Format days left display
                if days_left < 0:
                    days_left_text = "Expired"
                elif days_left == 0:
                    days_left_text = "Due Today"
                elif days_left == 1:
                    days_left_text = "1 day"
                else:
                    days_left_text = f"{days_left} days"
                
                self.homework_data.append({
                    "homework": assignment,
                    "homeworkId": assignment.ID,
                    "courseId": assignment.Course.ID,
                    "courseName": assignment.Course.CourseName,
                    "title": assignment.Title,
                    "deadline": assignment.Deadline.strftime("%Y-%m-%d %H:%M"),
                    "status": status,
                    "days_left": days_left_text,
                    "is_submitted": assignment.is_submitted_by(self.student),
                    "is_expired": now > assignment.Deadline,
                    "tag": tag
                })
        
        # Add to table with tags
        for homework in self.homework_data:
            self.homework_tree.insert("", tk.END, values=(
                homework["homeworkId"],
                homework["courseName"],
                homework["title"],
                homework["deadline"],
                homework["status"],
                homework["days_left"]
            ), tags=(homework["tag"],))
    
    def submit_assignment(self, assignment_id: str, student_id: str, content: str) -> tuple:
        """Submit assignment to assignment system"""
        success, msg = self.assignment_system.submit_assignment(assignment_id, student_id, content)
        if success:
            self.load_homework_data()  # Reload assignment data
        return success, msg
    
    def back_to_main(self):
        """Return to main interface"""
        self.app.ShowStudentMainFrame()

# ------------------------------
# 7. Student Main Interface
# ------------------------------
class StudentMainFrame(ttk.Frame):
    def __init__(self, parent: tk.Tk, app: "LMSApp", student: Student, user_system: UserSystem, 
                 course_system: CourseSystem, assignment_system: AssignmentSystem):
        super().__init__(parent, style="Main.TFrame")
        self.app = app
        self.student = student
        self.user_system = user_system
        self.course_system = course_system
        self.assignment_system = assignment_system
        self.parent = parent
        
        # Remove fixed size, use relative layout
        self.parent.geometry("")
        
        # Top navigation bar
        top_nav = ttk.Frame(self, style="Card.TFrame", height=70)
        top_nav.pack(fill=tk.X)
        top_nav.pack_propagate(False)
        
        # Welcome message
        welcome_frame = ttk.Frame(top_nav)
        welcome_frame.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=25)
        welcome_label = ttk.Label(
            welcome_frame, text=f"Welcome back, {student.EnglishName}", 
            font=("Microsoft YaHei", 12, "bold"), foreground="#1F2937"
        )
        welcome_label.pack(side=tk.LEFT, padx=0, pady=25)
        
        # Right button area
        btn_frame = ttk.Frame(top_nav)
        btn_frame.pack(side=tk.RIGHT, padx=20, pady=15)
        
        info_btn = ttk.Button(btn_frame, text="Personal Info", command=self.show_student_info, style="Secondary.TButton")
        info_btn.pack(side=tk.RIGHT, padx=10)
        
        logout_btn = ttk.Button(btn_frame, text="Logout", command=self.logout, style="Primary.TButton")
        logout_btn.pack(side=tk.RIGHT)
        
        # Main function area - using grid layout for responsive card arrangement
        main_frame = ttk.Frame(self, style="Main.TFrame")
        main_frame.pack(expand=True, fill=tk.BOTH, padx=50, pady=50)
        
        # Use grid layout for responsive card arrangement
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)
        
        # Course module card
        course_module = ttk.Frame(main_frame, style="Card.TFrame")
        course_module.grid(row=0, column=0, sticky=tk.NSEW, padx=15, pady=20)
        
        # Add card shadow effect
        course_module.configure(relief="ridge", borderwidth=0)
        
        # Responsive internal layout
        course_module.grid_rowconfigure(0, weight=1)
        course_module.grid_columnconfigure(0, weight=1)
        
        # Course module content
        ttk.Label(course_module, text="📚", font=("Microsoft YaHei", 40)).grid(row=0, column=0, pady=(30, 20))
        ttk.Label(course_module, text="Course Management", style="SubTitle.TLabel").grid(row=1, column=0, pady=(0, 20))
        
        # Course count statistics
        course_count_frame = ttk.Frame(course_module)
        course_count_frame.grid(row=2, column=0, pady=(0, 25))
        ttk.Label(course_count_frame, text=f"Total {len(student.Courses)} courses", style="Normal.TLabel").pack()
        
        course_btn = ttk.Button(
            course_module, text="Enter Course Management", command=self.enter_course_module, 
            style="Primary.TButton"
        )
        course_btn.grid(row=3, column=0, padx=40, pady=(0, 30), sticky=tk.EW)
        
        # Assignment module card
        homework_module = ttk.Frame(main_frame, style="Card.TFrame")
        homework_module.grid(row=0, column=1, sticky=tk.NSEW, padx=15, pady=20)
        
        # Add card shadow effect
        homework_module.configure(relief="ridge", borderwidth=0)
        
        # Responsive internal layout
        homework_module.grid_rowconfigure(0, weight=1)
        homework_module.grid_columnconfigure(0, weight=1)
        
        # Assignment module content
        ttk.Label(homework_module, text="📝", font=("Microsoft YaHei", 40)).grid(row=0, column=0, pady=(30, 20))
        ttk.Label(homework_module, text="Assignment Management", style="SubTitle.TLabel").grid(row=1, column=0, pady=(0, 20))
        
        # Assignment count statistics
        all_assignments = []
        for course_id in student.Courses:
            all_assignments.extend(self.assignment_system.get_assignments_by_course(course_id))
        
        submitted_count = sum(1 for a in all_assignments if a.is_submitted_by(student))
        pending_count = len(all_assignments) - submitted_count
        
        # Assignment statistics
        stats_frame = ttk.Frame(homework_module)
        stats_frame.grid(row=2, column=0, pady=(0, 25))
        ttk.Label(stats_frame, text=f"Pending: {pending_count} | Submitted: {submitted_count}", style="Normal.TLabel").pack()
        
        homework_btn = ttk.Button(
            homework_module, text="Enter Assignment Management", command=self.enter_homework_module, 
            style="Primary.TButton"
        )
        homework_btn.grid(row=3, column=0, padx=40, pady=(0, 30), sticky=tk.EW)
    
    def show_student_info(self):
        """Show student personal information"""
        StudentInfoWindow(self, self.student)
    
    def enter_course_module(self):
        """Enter course management module"""
        self.app.SwitchFrame(
            lambda root, app: CourseModuleFrame(
                root, app, self.student, self.user_system, self.course_system
            )
        )
    
    def enter_homework_module(self):
        """Enter assignment management module"""
        self.app.SwitchFrame(
            lambda root, app: HomeworkModuleFrame(
                root, app, self.student, self.user_system, self.course_system, self.assignment_system
            )
        )
    
    def logout(self):
        """Logout current user"""
        if messagebox.askyesno("Confirm Logout", "Are you sure you want to logout?"):
            self.parent.destroy()

# ------------------------------
# 8. Main Application Class
# ------------------------------
class LMSApp:
    def __init__(self, root: tk.Tk, student_id: str):
        self.root = root
        self.root.title("GT-OOP Management LMS - Student Portal")
        self.root.resizable(True, True)  # Allow window resizing
        self.root.minsize(800, 600)  # Set minimum size
        self.current_frame: Optional[ttk.Frame] = None
        self.student: Optional[Student] = None
        
        # Initialize data systems
        self._init_data_systems()
        
        # Load and validate student
        self._load_and_validate_student(student_id)
        
        # Setup style and show main interface
        SetupStyle()
        self.ShowStudentMainFrame()
    
    def _init_data_systems(self):
        """Initialize data systems"""
        data_dir = os.path.join(project_root, "Data")
        
        # Ensure data directory exists
        os.makedirs(data_dir, exist_ok=True)
        
        # Initialize system paths
        user_data_path = os.path.join(data_dir, "UserAccount.json")
        course_data_path = os.path.join(data_dir, "Course.json")
        assignment_data_path = os.path.join(data_dir, "Assignment.json")
        
        # Initialize course data file if not exists
        if not os.path.exists(course_data_path):
            with open(course_data_path, "w", encoding="utf-8") as f:
                json.dump([], f, ensure_ascii=False, indent=2)
        
        # Initialize assignment data file if not exists
        if not os.path.exists(assignment_data_path):
            with open(assignment_data_path, "w", encoding="utf-8") as f:
                json.dump([], f, ensure_ascii=False, indent=2)
        
        # Create system instances
        self.user_system = UserSystem(user_data_path)
        self.course_system = CourseSystem(course_data_path)
        self.assignment_system = AssignmentSystem(assignment_data_path, self.course_system, self.user_system)
    
    def _load_and_validate_student(self, student_id: str):
        self.student = self.user_system.get_user_by_id(student_id)
        
        if not self.student:
            messagebox.showerror("Login Failed", f"Student with ID {student_id} not found")
            self.root.destroy()
            sys.exit(1)
            
        if not isinstance(self.student, Student):
            messagebox.showerror("Type Error", "Retrieved user object is not of type Student")
            self.root.destroy()
            sys.exit(1)
    
    def SwitchFrame(self, frame_class: callable):
        """Switch interface frames"""
        if self.current_frame:
            self.current_frame.destroy()
            
        self.current_frame = frame_class(self.root, self)
        self.current_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
    
    def ShowStudentMainFrame(self):
        """Show student main interface"""
        self.SwitchFrame(
            lambda root, app: StudentMainFrame(
                root, app, self.student, self.user_system, self.course_system, self.assignment_system
            )
        )

# ------------------------------
# 9. Program Entry Point
# ------------------------------
if __name__ == "__main__":
    root = tk.Tk()
    app = LMSApp(root, "S001")  # Student ID
    root.mainloop()